package cn.lblbc.lib.view.selectRv

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import androidx.recyclerview.widget.RecyclerView

class LblSelectRvAdapter<T> : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private var mDataList = ArrayList<T>()
    private lateinit var mContext: Context
    val selectionItemList = mutableListOf<T>()
    var onItemClick: ((data: T) -> Unit)? = null
    lateinit var onSelectionChanged: (selectionItemList: List<T>) -> Unit
    lateinit var getLayoutResId: () -> Int
    lateinit var getCheckBoxResId: () -> Int
    lateinit var onBind: (itemView: View, data: T) -> Unit
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val data = mDataList[position]
        holder.itemView.setOnClickListener {
            onItemClick?.invoke(data)
        }
        onBind(holder.itemView, data)
        holder.itemView.findViewById<CheckBox>(getCheckBoxResId())
            .setOnCheckedChangeListener { _, isSelected ->
                if (isSelected) {
                    selectItem(data)
                } else {
                    disSelectItem(data)
                }
            }
    }

    fun setData(dataList: List<T>) {
        mDataList.clear()
        mDataList.addAll(dataList)
        notifyDataSetChanged()
        selectionItemList.clear()
        notifySelectionChanged()
    }

    fun clearData() {
        mDataList.clear()
        notifyDataSetChanged()
        selectionItemList.clear()
        notifySelectionChanged()
    }

    override fun getItemCount(): Int = mDataList.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        mContext = parent.context
        val view = LayoutInflater.from(mContext).inflate(getLayoutResId(), parent, false)
        return ViewHolder(view)
    }

    private fun notifySelectionChanged() {
        onSelectionChanged.invoke(selectionItemList)
    }

    fun selectItem(data: T) {
        selectionItemList.add(data)
        notifySelectionChanged()
    }

    private fun disSelectItem(data: T) {
        selectionItemList.remove(data)
        notifySelectionChanged()
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

}